﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq; 
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace HttpRequest
{
    public class ParseHttpRequest
    { 
        #region GetPic 
        ///
        /// 获取瓦片  
        /// <param name="picUrl">图片Http地址</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="timeOut">Request最大请求时间，如果为-1则无限制</param> 
        /// 
        public bool DownloadPicture(string picUrl, string savePath, int timeOut)
        {
            bool value = false;
            WebResponse response = null;
            Stream stream = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl);
                if (timeOut != -1)
                    request.Timeout = timeOut;

                response = request.GetResponse();
                stream = response.GetResponseStream();

                if (!response.ContentType.ToLower().StartsWith("text/"))
                    value = SaveBinaryFile(response, savePath);
            }
            finally
            {
                if (stream != null)
                    stream.Close();
                if (response != null)
                    response.Close();
            }
            return value;
        }
        public bool SaveBinaryFile(WebResponse response, string savePath)
        {
            bool value = false;
            byte[] buffer = new byte[1024];
            Stream outStream = null;
            Stream inStream = null;
            try
            {
                if (File.Exists(savePath)) File.Delete(savePath);
                outStream = System.IO.File.Create(savePath);
                inStream = response.GetResponseStream();
                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0) outStream.Write(buffer, 0, l);
                } while (l > 0);
                value = true;
            }
            finally
            {
                if(outStream!=null) outStream.Close();
                if(inStream!=null) inStream.Close();
            }
            return value;
        }

        public bool GetPicStream(string Url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream sm = response.GetResponseStream();
                MemoryStream ms = new MemoryStream();
                byte[] buffer = new byte[4096];
                int len;

                len = sm.Read(buffer, 0, 4096);
                while (len > 0)
                {
                    ms.Write(buffer, 0, len);
                    len = sm.Read(buffer, 0, 4096); 
                }
            }
            catch (WebException ex)
            {

                if (ex.Status == WebExceptionStatus.NameResolutionFailure)
                {
                    //域名无法解析 
                }
            }
            finally
            {
                
            }
            return true;
        } 
        #endregion  

        #region GetTiles
        public Bitmap GetTile(string Url)
        {
            Bitmap img = null;
            HttpWebRequest req;
            HttpWebResponse res = null;
            try
            {
                System.Uri httpUrl = new System.Uri(Url);
                req = (HttpWebRequest)(WebRequest.Create(httpUrl));
                req.Timeout = 180000; //设置超时值10秒
                req.UserAgent = "XXXXX";
                req.Accept = "XXXXXX";
                req.Method = "GET";
                res = (HttpWebResponse)(req.GetResponse());
                img = new Bitmap(res.GetResponseStream());//获取图片流    
                
                //img.Save(@"E:/" + DateTime.Now.ToFileTime().ToString() + ".png");//随机名
            }

            catch (Exception ex)
            {
                string aa = ex.Message;
            }
            finally
            {
                res.Close();
            }
            return img;
        }
        #endregion

        [DllImport("gdi32")]
        public static extern int DeleteObject(IntPtr o);

        public void Dele(IntPtr oo)
        {
            DeleteObject(oo);
        } 
        

        /// <summary>
        /// 将两张图片沿垂直方向进行拼接
        /// </summary>
        /// <param name="firstMap"></param>
        /// <param name="secondMap"></param>
        /// <returns></returns>
        public Bitmap MergeImageVertical(Bitmap firstMap, Bitmap secondMap)
        {
            Bitmap newMap = null;
            int firstW, firstH, secondW, secondH;
            firstW = firstMap.Width;
            firstH = firstMap.Height;
            secondW = secondMap.Width;
            secondH = secondMap.Height;

            BitmapData firstBD =
            firstMap.LockBits(new Rectangle(0, 0, firstW, firstH),
            ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            BitmapData secondBD =
            secondMap.LockBits(new Rectangle(0, 0, secondW, secondH),
            ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            int firstStride = firstBD.Stride;
            int secondStride = secondBD.Stride;

            System.IntPtr firstScan0 = firstBD.Scan0;
            System.IntPtr secondScan0 = secondBD.Scan0;

            int maxW = firstW;
            if (maxW < secondW)
                maxW = secondW;
            newMap = new Bitmap(maxW, firstH + secondH);
            BitmapData newBD =
            newMap.LockBits(new Rectangle(0, 0, maxW, firstH + secondH),
            ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            System.IntPtr newScan0 = newBD.Scan0;
            unsafe
            {
                int newMapStride = newBD.Stride;
                byte* pFirst = (byte*)(void*)firstScan0;
                byte* pSecond = (byte*)(void*)secondScan0;
                byte* pNew = (byte*)(void*)newScan0;
                int x, y, temp3W, tempYStride, tempYNewMapStride;
                byte temp1;
                //写入上边图像
                temp3W = 3 * firstW;
                for (y = 0; y < firstH; y++)
                {
                    tempYStride = y * firstStride;
                    tempYNewMapStride = y * newMapStride;
                    for (x = 0; x < temp3W; x++)
                    {
                        temp1 = pFirst[x + tempYStride];
                        pNew[x + tempYNewMapStride] = temp1;
                    }
                }

                //写入下边图像
                temp3W = 3 * secondW;
                for (y = 0; y < secondH; y++)
                {
                    tempYStride = y * secondStride;
                    tempYNewMapStride = (y + firstH) * (newMapStride);
                    for (x = 0; x < temp3W; x++)
                    {
                        temp1 = pSecond[x + tempYStride];
                        pNew[x + tempYNewMapStride] = temp1;
                    }
                }
                newMap.UnlockBits(newBD);
            } 
            firstMap.UnlockBits(firstBD);
            secondMap.UnlockBits(secondBD); 
            return newMap;
        } 


    }
} 

//namespace 图片拼接
//{
//    public partial class Form1 : Form
//    {
//        public Form1()
//        {
//            InitializeComponent();
//        }
//        string[,] picID = new string[76, 76];
//        Bitmap[,] pics = new Bitmap[76, 76];
//        Bitmap[] bbb = new Bitmap[76];
//        string path = "D:\\编程实验\\62535\\";
//        private void button1_Click(object sender, EventArgs e)
//        {
//            Bitmap firstmap = null;
//            Bitmap secondmap = null;
//            for (int i = 0; i < 76; i++)
//            {
//                //初始化第一张图、、、、、、、、、、、、、、、、、、、、、、、、
//                string FullName1 = path + picID[i, 0] + ".jpg";
//                FileInfo fi1 = new FileInfo(FullName1);
//                if (fi1.Length < 50) //fillinfo.length的单位是字节
//                {
//                    //将空的图补充为黑底图
//                    Bitmap newmap = new Bitmap(256, 256);
//                    Graphics g = Graphics.FromImage(newmap);
//                    //清除画布,背景设置为黑色
//                    g.Clear(System.Drawing.Color.Black);
//                    g.Dispose();
//                    newmap.Save(FullName1);
//                }
//                pictureBox1.Image = Image.FromFile(FullName1);
//                firstmap = new Bitmap(pictureBox1.Image);
//                //初始化第一张图、、、、、、、、、、、、、、、、、、、、、、、、 
//                for (int j = 0; j < 76; j++)
//                {
//                    //初始化第二张图、、、、、、、、、、、、、、、、、、、、、、、、
//                    string FullName2 = path + picID[i, j] + ".jpg";
//                    FileInfo fi2 = new FileInfo(FullName2);
//                    if (fi2.Length < 50) //fillinfo.length的单位是字节
//                    {
//                        //将空的图补充为黑底图
//                        Bitmap newmap = new Bitmap(256, 256);
//                        Graphics g = Graphics.FromImage(newmap);
//                        //清除画布,背景设置为黑色
//                        g.Clear(System.Drawing.Color.Black);
//                        g.Dispose();
//                        newmap.Save(FullName2);
//                    }
//                    pictureBox2.Image = Image.FromFile(FullName2);
//                    secondmap = new Bitmap(pictureBox2.Image);
//                    //初始化第二张图、、、、、、、、、、、、、、、、、、、、、、、、 
//                    Bitmap aaa = MergeImageVertical(secondmap, firstmap);
//                    firstmap = aaa;
//                }
//                Bitmap result = firstmap;
//                firstmap = null;
//                secondmap = null;
//                if (result != null)
//                {
//                    result.Save(path + (25266 + i).ToString() + ",9383.png", System.Drawing.Imaging.ImageFormat.Png);
//                }
//                result = null;
//                //MessageBox.Show(i.ToString());
//            } 
//        } 
//        private void Form1_Load(object sender, EventArgs e)
//        {
//            for (int i = 0; i < 76; i++) 
//            {
//                for (int j = 0; j < 76; j++)
//                {
//                    picID[i, j] = (25266 + i).ToString() + "," + (9383 + j).ToString();
//                }
//            }
//        } 
//}

